#!/usr/bin/python

#Calculate how many alarms are there in the evaluation interval.

import os.path
import math
import sys

#------------------------------------------------------------------------------
#Global variables
databaseFolder = '/home/sergi/work/1_SCDB'
resultsFolder = '/home/sergi/work/Alarms_detection/metric_results/'
CORPUS = ['S3', 'S4', 'S11', 'S12', 'S13', 'S14', 'S15', 'S16', 'S17', 'S18']
#CORPUS = ['S3']
SCENARIOS = ['SC1', 'SC2', 'SC3', 'SC4', 'SC5', 'SC6', 'SC7', 'SC8', 'SC9', 'SC10']
#SCENARIOS = ['SC1']
EXTRAS = [ '', '_2' ]
#TIERS = [ 'alarms', 'vocalizations', 'noises' ]
TIERS = [ 'alarms' ]

#Indexes of labels
START_TIME = 0
END_TIME = 1
CLASS = 2

class_of_interest = "al"
evaluation_interval = sys.argv[1] #in seconds
evaluation_interval = int(evaluation_interval)

#------------------------------------------------------------------------------
newpath = resultsFolder + '/' + 'evaluation_interval_' + str(evaluation_interval) + '/'
if not os.path.exists(newpath):
    os.makedirs(newpath)
outputFile2 = open(resultsFolder + '/' + 'evaluation_interval_' + str(evaluation_interval) + '/' + 'overall_last_interval.txt', 'w') #file containing overall last interval length
for session in CORPUS:
    newpath = resultsFolder + '/' + 'evaluation_interval_' + str(evaluation_interval) + '/' + session + '/'
    if not os.path.exists(newpath):
        os.makedirs(newpath)
    for scenario in SCENARIOS:
        for extra in EXTRAS:            
            for tier in TIERS:
                #The path to the corresponding .csv file
                path = databaseFolder + '/' + session + '/' + tier + 'Labelling/' + session + '_' + scenario + extra + '.csv'
                if not os.path.isfile(path):
                    continue
                else:            
                    with open(path) as fileID:
                        outputFile = open(newpath + session + '_' + scenario + extra + '.txt', 'w') #files containing stats
                        interval_index = 1
                        interval_counts = 0
                        interval_partials = 0
                        for line in fileID: #for each event label (can be al or ot)
                            labels = line.split(',') #obtain array with start_time, end_time, label
                            interval_start = (interval_index - 1) * evaluation_interval
                            interval_end = interval_index * evaluation_interval
                            if class_of_interest in labels[CLASS]:
                                if (float(labels[START_TIME]) == float(interval_end)):
                                    outputFile.write(str(interval_start) + '\t' + str(interval_end) + '\t' + str(interval_counts) + '\t' + str(interval_partials) + '\n')
                                    interval_index += 1
                                    interval_counts = 0
                                    interval_partials = 0
                                if (float(labels[END_TIME]) > float(interval_end) and float(labels[START_TIME]) != float(interval_end)): #span for more than 1 interval is not considered, since alarms are of max 1s length
                                    interval_partials += 1
                                    outputFile.write(str(interval_start) + '\t' + str(interval_end) + '\t' + str(interval_counts) + '\t' + str(interval_partials) + '\n')  
                                    interval_index += 1
                                    interval_counts = 0
                                    interval_partials = 1
                                else:
                                    interval_counts += 1
                            else: #for the ot class
                                previous_interval_index = interval_index
                                if (float(labels[END_TIME]) > float(interval_end)): #if ot event spans more than 1 interval 
                                    interval_index = int(math.ceil((float(labels[END_TIME]) - evaluation_interval)/evaluation_interval)+1)
                                if (float(labels[END_TIME]) >= float(interval_end) and interval_index - previous_interval_index >= 1):
                                    for x in range (int(previous_interval_index), int(interval_index)):
                                        interval_start = (x - 1) * evaluation_interval
                                        interval_end = x * evaluation_interval
                                        outputFile.write(str(interval_start) + '\t' + str(interval_end) + '\t' + str(interval_counts) + '\t' + str(interval_partials) + '\n')
                                        interval_counts = 0
                                        interval_partials = 0
                        if (float(labels[END_TIME]) - float(interval_start) - float(evaluation_interval) < 0): #calculate last interval
                            last_interval = str(float(labels[END_TIME]) - float(interval_start))
                        else:
                            last_interval = str(float(labels[END_TIME]) - float(interval_start) - float(evaluation_interval))
                        outputFile2.write(last_interval + '\n')
                        interval_index = 1
                        interval_counts = 0
                        interval_partials = 0
outputFile.close()
outputFile2.close()
